/*
 * Copyright 2011 Angel Sanadinov
 *
 * This file is part of VBox WMI.
 *
 * VBox WMI is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * VBox WMI is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with VBox WMI.  If not, see <http://www.gnu.org/licenses/>.
 */

package Utilities;

import java.util.Map.Entry;
import java.util.LinkedHashMap;

/**
 * A <code>LinkedHashMap</code> used for caching entries of type <code>V</code>.
 * <br><br>
 * Each <code>CacheMap</code> has a maximum number of entries and once reached,
 * the eldest entry is removed from the map.
 *
 * @param <K> the type of keys
 * @param <V> the type of values
 *
 * @see CacheMap#CacheMap(int)
 * @see CacheMap#CacheMap(int, float) 
 * @see LinkedHashMap
 * @see LinkedHashMap#removeEldestEntry(java.util.Map.Entry)
 *
 * @author Angel Sanadinov
 */
public class CacheMap<K, V> extends LinkedHashMap<K, V>
{
    private int maxCacheEntries = 0; //the maximum number of entrie to cache

    /**
     * Constructs a new <code>CacheMap</code> that has a size of <code>maxCacheEntries</code>.
     *
     * @param maxCacheEntries the maximum number of entries to be cached
     * @see CacheMap
     */
    public CacheMap(int maxCacheEntries)
    {
        super(maxCacheEntries, 0.75f, true);
        this.maxCacheEntries = maxCacheEntries;
    }

    /**
     * Constructs a new <code>CacheMap</code> that has a size of <code>maxCacheEntries</code>
     * and with a load factor of <code>loadFactor</code>.
     *
     * @param maxCacheEntries the maximum number of entries to be cached before the eldest is removed
     * @param loadFactor the map's load factor
     *
     * @see CacheMap
     * @see LinkedHashMap#LinkedHashMap(int, float)
     */
    public CacheMap(int maxCacheEntries, float loadFactor)
    {
        super(maxCacheEntries, loadFactor, true);
        this.maxCacheEntries = maxCacheEntries;
    }

    /**
     * Determines whether the eldest entry is to be removed.
     *
     * @param eldest the least recently inserted entry
     * @return <code>true</code> if the entry is to be removed or <code>false</code>
     *         otherwise
     *
     * @see LinkedHashMap#removeEldestEntry(java.util.Map.Entry) 
     */
    @Override
    protected boolean removeEldestEntry(Entry<K, V> eldest)
    {
        return (size() >= maxCacheEntries);
    }

}
